﻿cbuffer cbPerObject
{
	float4x4 WorldViewProjection;	
	float4x4 WorldView;	
	float4x4 View;	
	float4x4 InverseProjection;
	float4x4 ViewToLightProjection;
	float4x4 ViewToLightView;
}

cbuffer cbGlobal
{
	int2 targetSize;
	int2 previousSize;
    int2 textureSize;
}

SamplerState SrcSampler
{
	Filter = MIN_MAG_POINT_MIP_LINEAR;
    AddressU = Clamp;
    AddressV = Clamp;
};

Texture2D srcTexture;

struct App2VS
{
	float3 pos : POSITION;
	float3 col : COLOR;
	float3 normal : NORMAL;
};
struct VS2PS
{
	float4 pos : SV_Position;
	float3 viewRay : TEXCOORD0;
};
struct PS2GPU
{
	float4 value : SV_Target0;
};

void vs(App2VS IN, out VS2PS OUT)
{
	OUT.pos = float4(IN.pos, 1); //pass through for quad/etc
}
void ps(VS2PS IN, out PS2GPU OUT)
{
    /*
	float2 uv = IN.pos / targetSize * (((float2)previousSize) / textureSize);
    
    //uv *= 2;
    if(uv.x > 1 || uv.y > 1)
    {
        OUT.value = 0;
        return;
    }

    

    float2 uvPixOffset = 1.0f / previousSize;

	float4 value0 = srcTexture.Sample(SrcSampler, uv);
	float4 value1 = srcTexture.Sample(SrcSampler, float2(1,0) * uvPixOffset + uv);
	float4 value2 = srcTexture.Sample(SrcSampler, float2(0,1) * uvPixOffset + uv);
	float4 value3 = srcTexture.Sample(SrcSampler, float2(1,1) * uvPixOffset + uv);
    */
    
    float3 curPosFloat = float3((IN.pos.xy - float2(0.5, 0.5)) / targetSize * previousSize, 0);
    int3 curPos = int3(floor(curPosFloat.x), floor(curPosFloat.y), 0);


    float4 value0 = srcTexture.Load(curPos, int2(0, 0));
    float4 value1 = srcTexture.Load(curPos, int2(1, 0));
    float4 value2 = srcTexture.Load(curPos, int2(0, 1));
    float4 value3 = srcTexture.Load(curPos, int2(1, 1));
    /*
    if(targetSize.x < 1.5 && targetSize.y < 1.5)
    {
        OUT.value = value2;
        return;
    }*/


    int total = 0;
    float4 avg = 0;

    if(length(value0) != 0)
    {
        total++;
        avg += value0;
    }
    if(length(value1) != 0)
    {
        total++;
        avg += value1;
    }
    if(length(value2) != 0)
    {
        total++;
        avg += value2;
    }
    if(length(value3) != 0)
    {
        total++;
        avg += value3;
    }

    if(total == 0)
    {
        avg = 0;
    }
    else 
    {
        //avg = avg / total;
    }

    OUT.value = avg;
    //OUT.value = IN.pos.x == 0.5;
}
technique10 Render
{
	pass P0
	{
		SetGeometryShader( 0 );
		SetVertexShader( CompileShader( vs_4_0, vs() ) );
		SetPixelShader( CompileShader( ps_4_0, ps() ) );
	}
}